import axios, { AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
// 封装axios
const instance = axios.create({
    // baseURL: '/api',
    timeout: 5000
})

// 请求拦截
instance.interceptors.request.use((config => {
    // 如果有token就带上token发请求
    const token = localStorage.getItem("token");
    if(token){
        console.log("tokan: "+ token);
        if(config.headers){
            console.log("请求头带上token");
            config.headers["token"] = token;
        }
    }
    return config;
}), (err) => { Promise.reject(err) })

// 响应拦截 并做统一错误捕获
instance.interceptors.response.use(
    (response) => {
        const data = response.data as IResponse<any>;
        if (data.code !== 20000) {
            ElMessage.error(data.message);
        }
        return response.data;
    },
    (err) => {
        ElMessage.error("请求失败，错误信息：" + err.message);
        Promise.reject(err)
    })

export default instance;